﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace FileProcessSystem
{
   
    public partial class MainForm : Form
    {
        string filePath;//文件路径
        string content;//文件内容

            //统计文件行数、单词数
            Tuple<int, int> CountLinesAndWords(string content)
        {
            // 去除所有标点符号
            string noPunctuation = Regex.Replace(content, @"[^\w\s]", "");
            // 分割成行
            var lines = noPunctuation.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            // 过滤掉空行
            var nonEmptyLines = lines.Where(line => !string.IsNullOrWhiteSpace(line));
            // 统计行数
            int lineCount = nonEmptyLines.Count();
            // 将非空行连接起来并分割成单词
            var words = nonEmptyLines.SelectMany(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
            // 统计单词数
            int wordCount = words.Count();

            return Tuple.Create(lineCount, wordCount);
        }
        
        //删除源文件空行和注释
        string RemoveEmptyLinesAndComments(string content)
        {
           
            string[] lines = content.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            List<string> cleanedLines = new List<string>();

            foreach (var line in lines)
            {
                // 移除注释
                if (line.TrimStart().StartsWith("//"))
                {
                    continue;
                }
                // 如果不是空行，则添加到列表
                if (!string.IsNullOrWhiteSpace(line))
                {
                    cleanedLines.Add(line);
                }
            }

            return string.Join(Environment.NewLine, cleanedLines);
        }
        //统计文件单词出现次数
        Dictionary<string, int> CountWordOccurrences(string content)
        {
            // 去除所有标点符号
            string noPunctuation = Regex.Replace(content, @"[^\w\s]", "");
            // 分割成单词
            var words = noPunctuation.Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            // 统计每个单词的出现次数
            return words.GroupBy(word => word.ToLower())
                        .ToDictionary(group => group.Key, group => group.Count());
        }
    
    public MainForm()
        {
            InitializeComponent();
        }

        //用户选中一个.cs文件之后
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            nameTextBox.Text = openFileDialog1.FileName;
            filePath = openFileDialog1.FileName;
            // 读取文件内容
            content = File.ReadAllText(filePath);
        }

        //统计行数以及单词数
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {  //判断当前是否有文件被选中
                if (!openFileDialog1.CheckFileExists)
                    throw new Exception("当前未选中文件");
                //获得文件数据
                Tuple<int,int> tuple=CountLinesAndWords(content);
                MessageBox.Show("该文件的数据为（不含空格、空行、标点符号）" + Environment.NewLine +
                    "行数:" + tuple.Item1 + Environment.NewLine +
                    "单词数:" + tuple.Item2
                    );

            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message);
            }
        }

        //查看当前文件内容
        private void openFileLabel_Click(object sender, EventArgs e)
        {

        }


        //打开OpenFileDialog
        private void fileButton_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog(this);
        }



      
        //格式化
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                //判断当前是否有文件被选中
                if (!openFileDialog1.CheckFileExists)
                    throw new Exception("当前未选中文件");
                String newContent=RemoveEmptyLinesAndComments(content);
                //写入格式化后的内容
                File.WriteAllText(filePath, newContent );
                content = newContent;
                MessageBox.Show("已成功格式化文件");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //单词统计
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                //判断当前是否有文件被选中
                if (!openFileDialog1.CheckFileExists)
                    throw new Exception("当前未选中文件");
                Dictionary<String,int> dic=CountWordOccurrences(content);
                //打印的结果字符串
                String output=String.Empty;
                foreach (KeyValuePair<string, int> kvp in dic)
                {
                    output += kvp.Key + " " + kvp.Value + Environment.NewLine;
                }
                MessageBox.Show(output);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
